﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RonYee.Models;
using RonYee.Service;
using System.Web.Security;

namespace RonYee.Controllers
{
    public class CustomerController : Controller
    {
        RongeDb db = new RongeDb();
        //
        // GET: /Customer/

        [Authorize(Roles = "Admin")]
        public ActionResult Index()
        {

            RonYee.Models.MvcPage Model = new MvcPage();
            Model.CurrentPageIndex = 1;  //当前页 默认第一页

            int SkinCount = (Model.CurrentPageIndex - 1) * Model.PageSize;

            //测试用例。实际用自己的逻辑获取数据
            List<Customer> datesource = GetDataSource();//要分页的数据源
            Model.CustomerList = datesource.Where(r => r.CustomerId >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            //测试用例。实际用自己的逻辑获取数据

            //是否开启Ajax分页
            Model.IsAjax = true;
            Model.TotalCount = datesource.Count;//获取记录总数

            //获取分页数据
            Model.CustomerList = datesource.Where(r => r.CustomerId >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            return View(Model);

        }

        private List<Customer> GetDataSource()
        {
            var user = from b in db.Customers
                       orderby b.AddTime ascending
                       select b;
            List<Customer> model = new List<Customer>();
            foreach (var item in user)
            {
                model.Add(item);
            }
            return model;
        }

        [Authorize(Roles = "Admin")]
        public ActionResult PageIndex(RonYee.Models.MvcPage Model)
        {

            //分页数据源。自己写逻辑获取。


            int SkinCount = (Model.CurrentPageIndex - 1) * Model.PageSize;

            //测试用例。实际用自己的逻辑获取数据
            List<Customer> datesource = GetDataSource();//要分页的数据源
            Model.CustomerList = datesource.Where(r => r.CustomerId >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            //测试用例。实际用自己的逻辑获取数据

            Model.TotalCount = datesource.Count;//获取记录总数
            if (Request.IsAjaxRequest())  //是AJAX请求的话返回AJAX分页数据
            {
                Model.IsAjax = true;
                return View(Model);
            }
            else
            {
                Model.IsAjax = false;
                return this.PartialView("Index", Model);
            }
            //return View(Model);
        }

        [HttpPost]
        [Authorize(Roles = "Admin")]
        public ActionResult Search()
        {
            string sno = Request.Form["s_no"];
            string name = Request.Form["s_name"];
            DateTime start, end;
            start = Convert.ToDateTime("2012-1-1");
            end = Convert.ToDateTime("2100-1-1");
            if (Request.Form["s_time"].ToString() != "")
            {
                start = Convert.ToDateTime(Request.Form["s_time"]);
            }
            if (Request.Form["e_time"].ToString() != "")
            {
                end = Convert.ToDateTime(Request.Form["e_time"]);
            }

            //11
            if (sno != "" && name == "")
            {
                var user = from b in db.Customers
                           where b.CustomerNo == sno
                           orderby b.AddTime ascending
                           select b;
                return View(user);
            }
            else if (sno == "" && name != "")
            {
                var user = from b in db.Customers
                           where b.Login == name
                           orderby b.AddTime ascending
                           select b;
                return View(user);
            }
            else
            {
                var user = from b in db.Customers
                           where b.AddTime >= start && b.AddTime <= end
                           orderby b.AddTime ascending
                           select b;
                return View(user);
            }

        }


        [Authorize(Roles = "Admin")]
        public ActionResult Create() 
        {
            return View();
        }

        [Authorize(Roles = "Admin")]
        [HttpPost] 
        public ActionResult Create(Customer model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                model.AddTime = DateTime.Now;
                model.status = 1;
                Membership.CreateUser(model.Login, "abc123", model.Email, null, null, true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    // FormsAuthentication.SetAuthCookie(model.Login, false /* createPersistentCookie */);
                    try
                    {
                        db.Customers.Add(model);
                        db.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        ViewBag.Error = ex.Message;
                    }
                    return RedirectToAction("Index", "Customer");
                }
                else
                {
                    return View(model);
                }
            }
            else
            {

                // If we got this far, something failed, redisplay form
                return View(model);
            }
        }



        [Authorize(Roles = "Admin")]
        public ActionResult Details(int id)
        {
            var model=db.Customers.Find(id);
            var orderList=from o in db.Orders
                          where o.Username==model.Login
                          orderby o.OrderDate descending
                          select o;
            ViewData["OrderList"] = orderList;
            return View(model);
        }

        [Authorize(Roles = "Admin")]
        public ActionResult Edit(int id)
        {
            var model = db.Customers.Find(id);
            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Admin")]
        public ActionResult Edit(Customer model) 
        {
            model.status = Convert.ToInt32(Request.Form["UserState"]);
            model.UserType = Convert.ToInt32(Request.Form["UserType"]);
            if (ModelState.IsValid)
            {
                try
                {
                    var customer = db.Customers.Find(model.CustomerId);
                    UpdateModel(customer);
                    db.SaveChanges();
                    return View(model);
                }
                catch (Exception e)
                {
                    ModelState.AddModelError("", "修改失败，请查看详细错误信息:" + e);
                }
            }
            return View(model);
        }


    }
}
